<template>
  <div>
    <el-steps :active="active" finish-status="success" align-center>
      <el-step title="创建项目"></el-step>
      <el-step title="上传视频"></el-step>
      <el-step title="设置编码规则"></el-step>
      <el-step title="编码数据"></el-step>
      <el-step title="分析结果"></el-step>
    </el-steps>
    <el-divider></el-divider>
    <el-skeleton :loading=loading :rows="10" animated />
    <div  v-show="active!==0">
      <el-card shadow="hover">
        <el-descriptions title="项目信息">
          <el-descriptions-item label="项目名">{{this.project.projectName}}</el-descriptions-item>
          <el-descriptions-item label="项目类型">FIAS分析</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{this.project.createTime}}</el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
    <div v-show="active === 0 && loading===false">
      <el-card shadow="hover">
        <el-form ref="projectFormRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="项目名" prop="projectName">
            <el-input v-model="form.projectName" placeholder="请输入项目名" />
          </el-form-item>
          <el-form-item label="项目类型" prop="projectType">
            <el-select v-model="form.projectType">
              <el-option  key="FIAS" label="弗兰德斯分析" value="FIAS"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm">创建项目</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div v-show="active===1" style="width: 100%;display: flex;flex-direction: row;margin-top: 20px;justify-content: space-between" >
      <el-card style="width: 48%;">
        <div slot="header">
          <span><b>上传视频</b></span>
        </div>
        <VideoUpload ref="videoUpload"></VideoUpload>
      </el-card>
      <el-card style="width: 48%">
        <div slot="header">
          <span><b>设置参数</b></span>
        </div>
        <el-form ref="stConfigFormRef" :model="fiasConfig" :rules="fiasConfigRules" label-width="120px">
          <el-form-item label="采样间隔(s)" prop="interval">
            <el-input-number v-model="fiasConfig.interval"  :min="1" :max="60"></el-input-number>
          </el-form-item>
          <el-form-item label="采样开始时刻" prop="startTime">
            <el-time-select placeholder="起始时间"
                            v-model="fiasConfig.startTime"
                            :picker-options="{
                start:  this.time.startTime,
                step: formatTime(fiasConfig.interval),
                end: this.time.endTime
              }">
            </el-time-select>
          </el-form-item>
          <el-form-item label="采样结束时刻" prop="endTime">
            <el-time-select placeholder="结束时间"
                            v-model="fiasConfig.endTime"
                            :picker-options="{
                start: this.time.startTime,
                step: formatTime(fiasConfig.interval),
                end: this.time.endTime,
                minTime: fiasConfig.startTime
              }">
            </el-time-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="next">下一步</el-button>
            <el-button @click="resetForm2">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div v-show="active===2" style="height:500px;width: 100%;display: flex;flex-direction: row;margin-top: 20px;justify-content: space-between" >
      <el-card style="width: 100%">
        <div slot="header">
          <span><b>添加编码</b></span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="newCategory">
            <i class="el-icon-plus"></i>
            新增
          </el-button>
        </div>
        <div style="display: flex;flex-direction: column;">
          <div style="width: 100%;display: flex;flex-direction: column" v-for="(category, index) in categoryList"  :key="index">
            <div style="display: flex;flex-direction: row;width: 100%">
              <el-row style="width: 100%">
                <el-col :span="2">
                  <el-tag closable @close="handleClose(category)">
                    {{category.categoryName}}
                  </el-tag>
                </el-col>
                <el-col :span="2">
                  <div style="margin-top:10px;font-size: 12px;color: rgb(148, 137, 137);">
                    当前大类下有{{category.classSize}}个编码
                  </div>
                </el-col>
                <el-col style="min-height: 1px;display: flex;flex-direction: row;"  :span="18">
                  <div style="margin-right: 5px" v-for="(fiasClass , index) in category.classList" :key="index">
                    <el-tag type="success" closable @close="handleClose2(fiasClass)">
                      {{fiasClass.classNum}} {{fiasClass.className}}
                    </el-tag>
                  </div>
                </el-col>
                <el-col :span="2">
                    <el-button style="float: right; padding: 3px 0" type="text" @click="newClass(category.id)">
                      <i class="el-icon-plus"></i>
                      添加小类
                    </el-button>
                </el-col>
              </el-row>
            </div>
            <el-divider></el-divider>
          </div>
          <div>
            <el-button v-waves plain type="primary" style="width:10%;float: left;margin-top: 20px" @click="pre" >上一步</el-button>
            <el-button v-waves type="success" style="width:10%;float: right;margin-top: 20px" @click="nextToEncode" >下一步</el-button>
          </div>
        </div>
      </el-card>
    </div>
    <div v-show="active===3"  style="width: 100%;display: flex;flex-direction: row;margin-top: 20px;justify-content: space-between">
      <el-card style="width: 48%;">
        <div slot="header">
          <span><b>播放视频</b></span>
        </div>
        <video-player style="width: 97%"
                      class="video-player vjs-custom-skin"
                      ref="videoPlayer"
                      @canplay="onPlayerCanplay($event)"
                      @timeupdate="onPlayerTimeupdate($event)"
                      :options="playerOptions"/>
      </el-card>
      <el-card style="width: 48%;">
        <div slot="header">
          <span><b>编码区域</b></span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="startEncode">开始编码</el-button>
        </div>
        <div style="display: flex;flex-direction: column;">
          <div style="margin-bottom: 5px">编码时间间隔：{{this.fias.interval}}s</div>
          <div>
            当前编码时间段：<el-tag>{{ this.encodeTime.startTime }}</el-tag> -- <el-tag type="success">{{ this.encodeTime.endTime }}</el-tag>
          </div>
          <el-divider></el-divider>
          <el-form ref="encodeFormRef" label-width="90px" :model="encode" :rules="encodeRules">
            <el-form-item label="选择编码" prop="code">
              <el-cascader :options="options" clearable v-model="encode.code">
                <template slot-scope="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
            <el-form-item>
              <el-button v-waves plain type="primary"  @click="preCode" >上一个</el-button>
              <el-button v-waves v-if="!finishFlag" plain type="success" @click="nextCode" >下一个</el-button>
              <el-button v-waves v-else type="success" @click="encodeFias" >完成</el-button>
            </el-form-item>
          </el-form>
          <el-divider/>
          <div v-if="preFlag">
            <div>
              上个编码时间段：
              <el-tag>
                {{ this.preTime.startTime }}
              </el-tag>
              --
              <el-tag type="success">
                {{ this.preTime.endTime }}
              </el-tag>
            </div>
            <div style="margin-top: 10px">
              上个编码内容：{{this.preTime.preCode}}
            </div>
          </div>
        </div>
      </el-card>
    </div>
    <div v-show="active===4"  style="margin-top: 20px">
      <el-card style="width: 100%">
        <div slot="header">
          <span><b>折线分析</b></span>
          <el-button style="color:#67C23A;float: right; padding: 3px 0" type="text" @click="nextToDownload">下载数据</el-button>
        </div>
        <div style="display:flex;flex-direction: row;justify-content: left;">
          <el-transfer v-model="value"
                       :data="this.transfer"
                       filterable
                       filter-placeholder="输入编码名/编码编号"
                       :titles="['FIAS编码', '已选择分析项']"
                       @change="handleChange"
          >
            <el-button  slot="left-footer" size="small" @click="deletePolyline">减少折线</el-button>
            <el-button  slot="right-footer" size="small" @click="addPolyline">添加折线</el-button>
          </el-transfer>
          <div id="polyline" ref="echart" style="margin-left:20px; width: 980px;height:420px;"></div>
        </div>
      </el-card>
    </div>

    <div  v-show="active===5" style="width: 100%;display: flex;flex-direction: row;margin-top: 20px;justify-content: space-between">
      <el-card style="width: 100%">
        <div slot="header">
          <span><b>分析报告</b></span>
          <el-button style="color:#67C23A;float: right; padding: 3px 0" type="text" @click="preToPolyline">折线分析</el-button>
          <el-button style="color:#409EFF;float: right; padding: 3px 10px" type="text" @click="drawer = true">下载数据</el-button>
        </div>
        <div style="display:flex;flex-direction: row;justify-content: left;">
          <div id="radar"  style="width: 700px;height:400px;"></div>
          <div style="width:100%;margin-left: 20px;">
            <div>
              <b>分析详情</b>
            </div>
            <div style="width:100%;margin-top: 5px;display: flex;flex-direction: row; flex-wrap: wrap; justify-content: space-between;row-gap: 20px">
              <div style="width: 25%" v-for="(item, i) in resultList" :key="i">
                <el-statistic group-separator=","
                              :precision="3"
                              :value="item.value"
                              :title="item.title">
                  <template slot="prefix">
                    <i class="el-icon-s-data" style="color: blue"></i>
                  </template>
                </el-statistic>
              </div>
              <div style="width: 25%">
                <el-statistic :value="fias.time"
                              title="分析耗时(ms)"
                              group-separator=",">
                  <template slot="prefix">
                    <i class="el-icon-time" style="color: blue"></i>
                  </template>
                  <template slot="suffix">
                    ms
                  </template>
                </el-statistic>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <el-dialog title="新增大类" :visible.sync="dialogVisible" width="30%">
      <el-form ref="categoryFormRef" :model="category" :rules="categoryRulers" label-width="80px">
        <el-form-item label="大类名称" prop="name">
          <el-input placeholder="例如教师语言" v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCategory">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="新增编码" :visible.sync="dialogVisible2" width="30%">
      <el-form ref="classFormRef" :model="fiasClass" :rules="classRulers" label-width="80px">
        <el-form-item label="编码名称" prop="name">
          <el-input placeholder="例如鼓励表扬" v-model="fiasClass.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="编码编号" prop="num">
          <el-input placeholder="例如1" v-model="fiasClass.num" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="addClass">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="减少折线" :visible.sync="dialogVisible3" width="30%">
      <el-form :inline="true"  ref="deleteLineFormRef" :model="deleteLine" :rules="lineRulers" >
        <el-form-item label="折线名" label-width="80px" prop="name">
          <el-select v-model="deleteLine.id" placeholder="请选择需要删除的折线">
            <el-option
                v-for="item in lineInfo"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="deleteline">删除</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-drawer
        title="下载数据"
        :visible.sync="drawer"
        direction="rtl">
      <div style="margin-left:20px;display: flex;flex-direction: column;justify-content: center;align-items: center">
        <div><b>FIAS编码表</b></div>
        <div style="margin-top: 10px">
          <el-button type="primary"  plain  icon="el-icon-download" size="small" @click="download">下载</el-button>
          <el-button type="info" plain icon="el-icon-files" size="small" @click="preview">预览</el-button>
        </div>
        <el-divider></el-divider>
        <div><b>矩阵分析表</b></div>
        <div style="margin-top: 10px">
          <el-button type="primary"  plain  icon="el-icon-download" size="small" @click="downloadMatrixTable">下载</el-button>
          <el-button type="info" plain icon="el-icon-files" size="small" @click="previewMatrixTable">预览</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {addProject, getProject} from "@/api/myProject";
import VideoUpload from "@/component/VideoUpload.vue";
import {formatTime, timeToSec} from "@/utils/date";
import {
  addFIASCategory,
  addFIASClass, cascader,
  deleteFIAS,
  deleteFIASClass, deletePolyline,
  detail, encodeFias,
  fiasConfig, getCodeNum,
  getInfo, getPolyline, getPolylineInfo, getRadar, nextToDownload, nextToEncode, polyline, preToPolyline,
  preUpload, result, transfer
} from "@/api/fias";
import pubsub from "pubsub-js";
import Waves from "@/directives/waves/waves";

//按需引入echarts折线图
//https://echarts.apache.org/examples/zh/editor.html?c=line-stack
import * as echarts from 'echarts/core';
import {
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { LineChart,RadarChart } from 'echarts/charts';
import { UniversalTransition } from 'echarts/features';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([
  TitleComponent,
  ToolboxComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  LineChart,
  RadarChart,
  CanvasRenderer,
  UniversalTransition
]);

export default {
  name: "FIAS",
  components: {VideoUpload},
  directives:{Waves},
  data(){
    return{
      drawer: false,//抽屉组件
      resultList:[],//分析结果列表
      title:"分析成功，耗时",
      lineInfo:[], //删除折线信息
      deleteLine: {}, //删除折线对象
      transfer: [], //数据
      value: [], //传输的值
      transferRight:[], //右侧数组
      myChart:'',
      option:'',
      option1:'',
      myChart1:'',
      startFlag:false, //开始编码标记
      finishFlag:false, //编码是否完成标记
      newClassId:'',//新增编码时传递的参数
      categoryList:[], //分类列表
      dialogVisible:false, //对话框
      dialogVisible2:false, //对话框
      dialogVisible3:false,
      category:{
        name:'' //大类名
      },
      fiasClass:{
        name:'', //小类名称
        num:'' //小类编号
      },
      classInfo:{},
      infoList:[], //历史编码信息列表，随codeList更新
      fias:{
        id:'',
        fiasStatus:'',
      },
      //时间选择器
      time:{
        startTime:'00:00',
        endTime:'',
        step:'',
      },
      fiasConfig:{
        interval:5,
        id:'',
        duration:'',
        endTime:"00:00",
        startTime:'00:00'
      },
      loading:false,
      id:this.$route.query.id,
      active: 0,
      form:{
        projectName:"",
        projectType:""
      },
      project:{},
      pubId:'',
      options:[],//编码参数
      preFlag:false,
      encode:{
        //当前编码数据
        code:''
      },
      //编码数据
      codeList:[],
      //上个编码时间段
      preTime:{
        startTime:'',
        endTime:'',
        preCode:''
      },
      //编码时间段
      encodeTime:{
        startTime:"",
        endTime:""
      },
      //播放器设置
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4",// 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
          src: "" // url地址
        }],
        poster: "", // 你的封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true  // 全屏按钮
        }
      },
    }
  },
  methods:{
    formatTime,

    download(){
      window.location.href = this.fias.codeTable;
    },
    preview(){
      var url =  this.fias.codeTable; //要预览文件的访问地址
      // eslint-disable-next-line no-undef
      window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
    },
    downloadMatrixTable(){
      window.location.href = this.fias.matrixTable;
    },
    previewMatrixTable(){
      var url =  this.fias.matrixTable; //要预览文件的访问地址
      // eslint-disable-next-line no-undef
      window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
    },
    //返回上一步折线分析
    preToPolyline(){
      preToPolyline(this.fias.id).then(()=>{
        this.getFIAS()
      })
    },
    //前往下载数据页面
    nextToDownload(){
      nextToDownload(this.fias.id).then(()=>{
        this.getFIAS()
      })
    },
    //执行删除的方法
    deleteline(){
      this.$refs.deleteLineFormRef.validate(valid => {
        if (valid) {
          this.dialogVisible3=false
          deletePolyline(this.deleteLine.id).then(()=>{
            this.getFIAS()
          })
        }
      })
    },
    //删除曲线
    deletePolyline(){
      getPolylineInfo(this.fias.id).then(res=>{
        this.dialogVisible3=true
        this.lineInfo=res.data
      })
    },
    //添加折线
    addPolyline(){
      if (this.transferRight.length===0){
        this.$notify({
          title: 'EasyCTBA',
          message: '未选择分析项！',
          type: 'error',
          duration: '3000',
          offset: 100
        });
      }else {
        this.$prompt('请输入折线名', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          polyline({
            id:this.fias.id,
            ids:this.transferRight,
            name:value
          }).then(()=>{
              this.getFIAS()
          })
        })
      }
    },
    //穿梭框改变时触发的回调函数
    handleChange(value, direction, movedKeys) {
      this.transferRight=value
      console.log(value);
      console.log(direction)
      console.log(movedKeys)
    },
    //获取编码对应的编号
    async getCodeLabel(id){
      await getCodeNum(id).then(res=>{
        this.classInfo = res.data
      })
      return this.classInfo
    },
    //编码FIAS
    encodeFias(){
      encodeFias(this.fias.id,{
        codeList : this.codeList
      }).then(()=>{
        this.$notify({
          title: 'EasyCTBA',
          message: '分析成功！',
          type: 'success',
          duration: '1000',
          offset: 100
        });
        this.getFIAS()
      })
    },
    //上一个编码
    preCode(){
      if (this.startFlag===false){
        this.$notify({
          title: 'EasyCTBA',
          message: '请点击开始编码！',
          type: 'error',
          duration: '3000',
          offset: 100
        });
      }else {
        //未检测到上个编码
        console.log(this.codeList)
        if (this.codeList.length === 0) {

          this.$notify({
            title: 'EasyCTBA',
            message: '没有上个编码！',
            type: 'error',
            duration: '3000',
            offset: 100
          });
        } else {
          //回退编码信息
          this.encodeTime.endTime=this.encodeTime.startTime
          this.encodeTime.startTime=formatTime(timeToSec(this.encodeTime.endTime)-this.fias.interval)
          let pre=this.infoList.pop()
          this.codeList.pop() //弹出编码列表

          this.encode.code = [pre.categoryId,pre.id]
          //没有上个编码了
          if (this.codeList.length === 0){
            this.preFlag=false
          }else {
            //回退上一个编码信息
            this.preTime.endTime=this.encodeTime.startTime
            this.preTime.startTime=formatTime(timeToSec(this.preTime.endTime)-this.fias.interval)
            let pre2=this.infoList.at(-1)
            this.preTime.preCode=pre2.classNum+" - "+pre2.className
          }
        }
      }
    },
    //下一个编码
    nextCode(){
      if (this.startFlag===false){
        this.$notify({
          title: 'EasyCTBA',
          message: '请点击开始编码！',
          type: 'error',
          duration: '3000',
          offset: 100
        });
      }else{
        this.$refs.encodeFormRef.validate(valid => {
          if (valid) {
            let code="NULL"
            let label="NULL"
            this.getCodeLabel(this.encode.code.at(1)).then(res=>{
              this.infoList.push(res)
              code=res.classNum
              label=res.className

              //编码时间超过视频时间，结束编码
              console.log(this.encodeTime.endTime)
              if (timeToSec(this.encodeTime.endTime)>=this.fias.duration){
                this.finishFlag=true;
              }

              //修改上个编码时间段
              if (this.codeList.length===0){
                this.preFlag=true
              }
              this.preTime.startTime=this.encodeTime.startTime
              this.preTime.endTime=this.encodeTime.endTime
              this.preTime.preCode=code+" - "+label

              this.codeList.push(code)
              //修改编码时间段
              this.encodeTime.startTime=this.encodeTime.endTime
              this.encodeTime.endTime=formatTime(timeToSec(this.encodeTime.startTime)+this.fias.interval)

              this.$refs.videoPlayer.player.play()


            })
          }
        })
      }
    },
    //开始编码
    startEncode(){
      this.startFlag=true;
      this.$refs.videoPlayer.player.currentTime(timeToSec(this.fias.startTime))
      this.$refs.videoPlayer.player.play()
    },
    //视频时间变化回调
    onPlayerTimeupdate(player){
      if (player.currentTime() >= timeToSec(this.encodeTime.endTime)){
        //当前时间大于编码结束时间
        player.pause()
      }
    },
    //视频准备完毕回调
    onPlayerCanplay(player){
      console.log(player.currentTime())
    },
    //获取视频时长
    setTime(data){
      this.fiasConfig.duration=data
      this.time.endTime=formatTime(data)
      this.time.startTime="00:00"
    },
    //提交表单
    submitForm(){
      this.$refs.projectFormRef.validate(valid => {
        if (valid) {
          addProject(this.form).then((res)=>{
            this.getProject(res.data)
            this.active=1
            this.$notify({
              title: 'EasyCTBA',
              message: '新建成功！',
              type: 'success',
              duration: '2000',
              offset: 100
            });
          })
        }
      })
    },
    //重置表单
    resetForm(){
      this.form={}
    },
    //获取项目详情
    getProject(id){
      getProject(id).then((res)=>{
        this.project=res.data
        this.getFIAS() //同步执行
      });
      if (this.project==={}){
        this.$notify({
          title: 'EasyCTBA',
          message: '参数异常！',
          type: 'error',
          duration: '2000',
          offset: 100
        });
      }
    },
    getFIAS(){
      getInfo(this.project.id).then(res=>{
        this.fias=res.data
        if (this.fias.fiasStatus==="upload"){
          this.active=1
        }else if (this.fias.fiasStatus==="ruler"){
          this.active=2
        }else if (this.fias.fiasStatus==="encode"){
          this.playerOptions.sources[0].src=this.fias.videoUrl
          this.playerOptions.poster=this.fias.videoUrl+"?x-oss-process=video/snapshot,t_1000,m_fast"
          this.encodeTime.startTime="00:00"
          this.encodeTime.endTime=formatTime(timeToSec(this.encodeTime.startTime)+this.fias.interval)

          cascader(this.fias.id).then(res=>{
            this.options=res.data
          })

          this.active=3;

        }else if (this.fias.fiasStatus==="result"){
          transfer(this.fias.id).then(res=>{
            this.transfer=res.data
          })
          getPolyline(this.fias.id).then(res=>{
            var option = this.myChart.getOption();

            //清空option
            option.legend[0].data=[]
            option.series=[]

            for (const resData of res.data) {
              option.legend[0].data.push(resData.legend)
              option.series.push(resData.series)
            }
            //第二个参数表示重新绘制整个图标，否则减少数据时不会刷新
            option && this.myChart.setOption(option,true);
          })
          this.active=4
        } else if (this.fias.fiasStatus==="download"){
          getRadar(this.fias.id).then(res=>{
            var option = this.myChart1.getOption();
            option.radar[0].indicator=res.data.indicator
            option.series[0].data[0].value=res.data.value
            this.myChart1.setOption(option,true);
          })
          result(this.fias.id).then(res=>{
            this.resultList=res.data
          })
          this.active=5
        } else {
          this.active=0
        }
      });
    },
    //在上传数据界面点击下一步
    next(){
      this.fiasConfig.id=this.fias.id
      fiasConfig(this.fiasConfig).then(()=>{
        this.getFIAS()
        this.$notify({
          title: 'EasyCTBA',
          message: '操作成功！',
          type: 'success',
          duration: '2000',
          offset: 100
        });
      })
    },
    resetForm2(){
      this.fiasConfig.interval=5
      this.fiasConfig.startTime="00:00"
      this.fiasConfig.endTime=formatTime(this.fiasConfig.duration)
    },
    //新增大类分类
    newCategory(){
      this.dialogVisible=true
    },
    //新增小类
    newClass(id){
      this.newClassId=id
      this.dialogVisible2=true
    },
    //新增编码大类
    addCategory(){
      addFIASCategory({
        name: this.category.name,
        id:this.fias.id
      }).then(()=>{
        this.$notify({
          title: 'EasyCTBA',
          message: '添加成功！',
          type: 'success',
          duration: '2000',
          offset: 100
        });
        this.listCategory()
        this.dialogVisible=false
      })
    },
    //新增编码
    addClass(){
      addFIASClass({
        name:this.fiasClass.name,
        id: this.newClassId,
        classNum:this.fiasClass.num
      }).then(()=>{
        this.$notify({
          title: 'EasyCTBA',
          message: '添加成功！',
          type: 'success',
          duration: '2000',
          offset: 100
        });
        this.listCategory()
        this.dialogVisible2=false
      })
    },
    //查询编码
    listCategory(){
      detail(this.fias.id).then((res)=>{
        this.categoryList=res.data
      })
    },
    //删除标签的回调函数
    handleClose(category){
      deleteFIAS(category.id).then(()=>{
        this.listCategory()
        this.$notify({
          title: 'EasyCTBA',
          message: '删除成功！',
          type: 'success',
          duration: '2000',
          offset: 100
        });
      })
    },
    //删除编码的回调函数
    handleClose2(fiasClass){
      deleteFIASClass(fiasClass.id).then(()=>{
        this.listCategory()
        this.$notify({
          title: 'EasyCTBA',
          message: '删除成功！',
          type: 'success',
          duration: '2000',
          offset: 100
        });
      })
    },
    //编码规则页面点击上一步
    pre(){
      preUpload(this.fias.id).then(()=>{
        this.getFIAS()
      })
    },
    nextToEncode(){
      nextToEncode(this.fias.id).then(()=>{
        this.getFIAS()
      })
    }
  },
  created() {
    this.$nextTick(()=>{
      var chartDom1 = document.getElementById('radar');
      var chartDom = document.getElementById('polyline');
      this.myChart = echarts.init(chartDom);
      this.myChart1 = echarts.init(chartDom1);
      this.option1 = {
        title:{
          text: "编码行为占比"
        },
        tooltip:{
          show:true,
          trigger: "item",
          confine: true  //解决浮窗被截断问题
        },
        radar: {
          // shape: 'circle',
          indicator: []
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        series: [
          {
            type: 'radar',
            data: [
              {
                value: [],
                name: '各编码行为占比',
                label: {
                  normal: {
                    show: true,
                    formatter:function(params) {
                      return params.value;
                    }
                  }
                }
              },
            ]
          }
        ]
      };
      this.option = {
        title: {
          text: '折线图'
        },
        tooltip: {
          trigger: 'axis'
        },
        //图例
        legend: {
          data: []
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'value',
          name:'时间(单位/分钟)',
          nameLocation:'center'
        },
        yAxis: {
          type: 'value',
          name:'次数(单位/次)',
          nameLocation:'center'
        },
        //数据
        series: []
      };
      this.option && this.myChart.setOption(this.option,true);
      this.option1 && this.myChart1.setOption(this.option1,true);
    })
  },
  mounted() {
    this.pubId = pubsub.subscribe('duration', (_,data) => {
      this.setTime(data)
    })

    const id=this.id
    if (id){
      this.loading = true
      getProject(id).then((res)=>{
        this.project=res.data
        getInfo(this.project.id).then(res=>{
          this.fias=res.data
          //传递参数给视频上传组件
          pubsub.publish('initVideo', {
            url:this.fias.videoUrl,
            id:this.fias.id,
            type:'FIAS'
          })
          if (this.fias.fiasStatus==="upload"){
            this.active=1
          } else if (this.fias.fiasStatus==="ruler"){

            this.listCategory()
            this.active=2
          } else if (this.fias.fiasStatus==="encode"){

            this.playerOptions.sources[0].src=this.fias.videoUrl
            this.playerOptions.poster=this.fias.videoUrl+"?x-oss-process=video/snapshot,t_1000,m_fast"
            this.encodeTime.startTime="00:00"
            this.encodeTime.endTime=formatTime(timeToSec(this.encodeTime.startTime)+this.fias.interval)
            cascader(this.fias.id).then(res=>{
              this.options=res.data
            })
            this.active=3

          }else if (this.fias.fiasStatus==="result"){
            transfer(this.fias.id).then(res=>{
              this.transfer=res.data
            })
            getPolyline(this.fias.id).then(res=>{
              var option = this.myChart.getOption();
              //清空option
              option.legend[0].data=[]
              option.series=[]

              for (const resData of res.data) {
                option.legend[0].data.push(resData.legend)
                option.series.push(resData.series)
              }
              this.myChart.setOption(option,true);
            })
            this.active=4
          }else if (this.fias.fiasStatus==="download"){
            getRadar(this.fias.id).then(res=>{
              var option = this.myChart1.getOption();
              option.radar[0].indicator=res.data.indicator
              option.series[0].data[0].value=res.data.value
              this.myChart1.setOption(option,true);
            })
            result(this.fias.id).then(res=>{
              this.resultList=res.data
            })
            this.active=5
          } else {
            this.active=0
          }
          this.loading=false
        });
      });
    }
  },
  computed:{
    rules(){
      return{
        projectName: [
          { required: true, message: "项目名不能为空", trigger: "blur" }
        ],
        projectType: [
          { required: true, message: "项目类型不能为空", trigger: "change" }
        ],
      }
    },
    fiasConfigRules(){
      return{
        startTime:[
          { type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime:[
          { type: 'date', required: true, message: '请选择结束', trigger: 'change' }
        ],
        interval:[
          { type: 'number', required:true, message: '请输入正确数据', trigger: 'blur' }
        ]
      }
    },
    categoryRulers(){
      return{
        name:[
          { required: true, message: "大类名称不能为空", trigger: "blur" }
        ]
      }
    },
    classRulers(){
      return{
        name:[
          { required: true, message: "编码名称不能为空", trigger: "blur" }
        ],
        num:[
          { required: true, message: "编号不能为空", trigger: "blur" }
        ]
      }
    },
    encodeRules(){
      return{
        code:[
          { required:true,message:'请选择编码类型',trigger:'blur'}
        ]
      }
    },
    lineRulers(){
      return{
        id:[
          { required:true,message:'请选择需要删除的折线名',trigger:'blur'}
        ]
      }
    }
  },
  beforeDestroy() {
    pubsub.unsubscribe(this.pubId)
  },
}
</script>

<style scoped>

</style>